package com.g8.pethospitallearnbackend.service.impls;

import com.g8.pethospitallearnbackend.entity.EmailSend;
import com.g8.pethospitallearnbackend.service.EmailService;
import jakarta.mail.MessagingException;
import jakarta.mail.internet.MimeMessage;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMailMessage;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

@Slf4j
@Service
@RequiredArgsConstructor
// 事务管理的注解
@Transactional(propagation = Propagation.SUPPORTS, readOnly = true, rollbackFor = Exception.class)
public class EmailServiceImpl implements EmailService {

    @Value("${spring.mail.email}")
    private String email;
    @Value("{spring.mail.host}")
    private String host;
    @Value("${spring.mail.port}")
    private String port;
    @Value("${spring.mail.username}")
    private String username;
    @Value("${spring.mail.password}")
    private String password;

    @Autowired
    private JavaMailSender mailSender;

    /**
     * 发送简单文字邮件信息
     * @param emailSend
     */
    @Override
    public void sendSimpleEmail(EmailSend emailSend) {
        // 读取邮箱配置
        if (email == null || host == null || port == null || username == null || password == null) {
            throw new RuntimeException("邮箱配置异常");
        }
//        MailAccount account = new MailAccount();
//        account.setHost(host);
//        account.setPort(Integer.parseInt(port));
//        // 设置发送人邮箱
//        account.setFrom(username + "<" + email + ">");
//        // 设置发送人名称
//        account.setUser(username);
//        // 设置发送授权码
//        account.setPass(password);
//        account.setAuth(true);
//        // ssl方式发送
//        account.setSslEnable(true);
//        // 使用安全连接
//        account.setStarttlsEnable(true);
//        try {
////            MailUtil.send(account,emailSend.getTos(), emailSend.getSubject(), emailSend.getContent(), false);
////            Mail.create(account)
////                    .setTos(emailSend.getTos().toArray(new String[size]))
////                    .setTitle(emailSend.getSubject())
////                    .setContent(emailSend.getContent())
////                    .setHtml(true)
////                    //关闭session
////                    .setUseGlobalSession(false)
////                    .send();
//        } catch (Exception e) {
//            throw new RuntimeException(e.getMessage());
//        }

        // 发送邮件
        SimpleMailMessage mailMessage = new SimpleMailMessage();
        // 设置发送人的邮箱
        mailMessage.setFrom(username);
        // 接受的邮箱
        mailMessage.setTo(emailSend.getTo());
        // 标题
        mailMessage.setSubject(emailSend.getSubject());
        // 内容
        mailMessage.setText(emailSend.getContent());

        mailSender.send(mailMessage);
    }

    /**
     * 发送复杂邮件信息
     * 使用模版的邮件发送
     * @param emailSend
     */
    @Override
    public void sendComplexEmail(EmailSend emailSend) {
        // 读取邮箱配置
        if (email == null || host == null || port == null || username == null || password == null) {
            throw new RuntimeException("邮箱配置异常");
        }
        MimeMessage mimeMessage = mailSender.createMimeMessage();
        try {
            MimeMessageHelper messageHelper = new MimeMessageHelper(mimeMessage, true, "UTF-8");
            // 设置邮件发件人
            messageHelper.setFrom(username);
            // 设置邮件接收人（可多人）
            messageHelper.setTo(emailSend.getTo());
            // 设置邮件抄送，不过这里没有
//            String[] ccArray = emailSend.getCcArray();
//            if (ccArray.length > 0) {
//                messageHelper.setCc(ccArray); // 普通抄送[邮件接收人可以看到抄送给谁了]
////                messageHelper.setBcc(ccArray); // 盲抄送[邮件接收人可以看不到抄送给谁了]
//            }
            // 设置邮件主题
            messageHelper.setSubject(emailSend.getSubject());
            // 加上模板的内容
            messageHelper.setText(emailSend.getContent(), true);
            // 下面这俩在这里都没用
//            // 批量处理嵌入式资源
//            Map<String, String> inlineMap = email.getInlineMap();
//            for (Map.Entry<String, String> entry : inlineMap.entrySet()) {
//                String contentId = entry.getKey();
//                String filePath = entry.getValue();
//                // 设置嵌入式资源
//                messageHelper.addInline(contentId, new File(filePath));
//            }
//            // 批量处理附件
//            List<String> attachmentList = email.getAttachmentList();
//            for (int i = 0; i < attachmentList.size(); i++) {
//                String filePath = attachmentList.get(i);
//                String fileName = i + "-" + filePath.substring(filePath.lastIndexOf(File.separator));
//                // 设置附件
//                messageHelper.addAttachment(fileName, new File(filePath));
//            }
            mailSender.send(mimeMessage);
        } catch (MessagingException e) {
            throw new RuntimeException(e);
        }
    }


}
